package com.hjl.sr.remoting;

import java.util.Map;

public class EncryptContextHolder {

	private static final ThreadLocal<EncryptContext> tlEncryptContext = new ThreadLocal<EncryptContext>();
	
	private EncryptContextHolder() {}
	
	public static void setEncryptContext(EncryptContext encryptContext) {
		EncryptContext ec = tlEncryptContext.get();
		if (ec == null) {
			tlEncryptContext.set(encryptContext);
		} else if (ec instanceof LazyEncryptContext) {
			Map<String, String> headers = ((LazyEncryptContext)ec).getHeaders();
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				encryptContext.addHeader(entry.getKey(), entry.getValue());
			}
		} else {
			tlEncryptContext.set(encryptContext);
		}
		
	}
	
	public static void clearEncryptContext() {
		tlEncryptContext.remove();
	}
	
	public static EncryptContext getEncryptContext() {
		EncryptContext ec = tlEncryptContext.get();
		if (ec != null) {
			return ec;
		}
		ec = new LazyEncryptContext();
		tlEncryptContext.set(ec);
		return ec;
	}
	
}
